package com.starsky.websocket.server;

import com.starsky.websocket.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty server
 */
public class NettyServer {
    private Logger log = LoggerFactory.getLogger(this.getClass()); // 日志对象

    /**
     * 不需要url参数，推送消息
     *
     * @throws Exception
     */
    public void start() throws Exception {

        //第一个线程组是用于接收Client连接的
        EventLoopGroup group = new NioEventLoopGroup();
        //第二个线程组是用于实际的业务处理操作的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        try {
            //创建一个启动NIO服务的辅助启动类ServerBootstrap
            ServerBootstrap sb = new ServerBootstrap();
            //设置TCP连接的缓冲区大小
            sb.option(ChannelOption.SO_BACKLOG, 1024);
//			//设置发送缓冲大小
//            sb.option(ChannelOption.SO_SNDBUF, 32 * 1024);
//			//设置接收缓冲大小
//            sb.option(ChannelOption.SO_RCVBUF, 32 * 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(12345)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.info("收到新连接");
                            // websocket协议本身是基于http协议的，所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            // 以块的方式来写的处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws"));
                            //将自定义的serverHandler加入到管道中
                            ch.pipeline().addLast(new WebSocketHandler());
                        }
                    });
            ////服务器异步创建绑定，也可以绑定多个端口
            ChannelFuture cf = sb.bind().sync();
//			ChannelFuture cf2 = sb.bind().sync();
            log.info(NettyServer.class + " 启动正在监听： " + cf.channel().localAddress());
            ////异步等待关闭 服务器通道
            cf.channel().closeFuture().sync();
        } finally {
            // 释放线程池资源
            group.shutdownGracefully().sync();
            bossGroup.shutdownGracefully().sync();
        }
    }
}
